package com.fecean.aabbc.netty.client.init;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * NettyClient
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-02-24 10:14
 * @blame Team
 */
@Slf4j
@Component
public class NettyClient {

    @Resource
    NettyClientInitializer nettyClientInitializer;

    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                //该参数的作用就是禁止使用Nagle算法，使用于小数据即时传输
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioSocketChannel.class)
                .handler(nettyClientInitializer);
        try {
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8090).sync();
            log.info("客户端成功....");
            // 等待连接被关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("客户端报错：", e);
        }finally {
            log.info("group.shutdownGracefully()");
            group.shutdownGracefully();
        }
    }
}
